//
//  EJSEditAddressViewController.m
//  EnjoyShoppingStreet
//
//  Created by lifayu on 2017/12/13.
//  Copyright © 2017年 lifayu. All rights reserved.
//

#import "EJSEditAddressViewController.h"
#import "ZJSwitch.h"
#import "EJSEditAddressRequest.h"
#import "EJSGetAreaRequest.h"
#import "DJShowSelectTool.h"
#import "EJSAddressModel.h"

@interface EJSEditAddressViewController ()

@property (weak, nonatomic) IBOutlet UILabel *editAddressTitleLabel;
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UILabel *countryLabel;
@property (weak, nonatomic) IBOutlet UILabel *provinceLabel;
@property (weak, nonatomic) IBOutlet UITextField *cityTextField;
@property (weak, nonatomic) IBOutlet UITextField *streetTextField;
@property (weak, nonatomic) IBOutlet UIButton *defaultAddressButton;
@property (weak, nonatomic) IBOutlet UITextField *postcodeTextField;
//@property (weak, nonatomic) IBOutlet UITextField *companyNameTextField;
//@property (weak, nonatomic) IBOutlet UITextField *taxNumberTextField;
//@property (weak, nonatomic) IBOutlet UISwitch *isTaxCompany;
@property (weak, nonatomic) IBOutlet UITextField *wechatNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *emailTextField;
@property (weak, nonatomic) IBOutlet UITextField *remarkTextField;
@property (weak, nonatomic) UITextField *previousTextField;

@property (strong, nonatomic) UIButton *saveAddressButton;

@property (strong, nonatomic) EJSAreaModel *country;
@property (strong, nonatomic) EJSAreaModel *province;
@property (strong, nonatomic) EJSAreaModel *city;

@end

@implementation EJSEditAddressViewController

+ (instancetype)viewController
{
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Mine" bundle:nil];
    return [storyBoard instantiateViewControllerWithIdentifier:@"EJSEditAddressViewController"];
}

//#pragma mark Setter/Getter
//- (NSMutableArray *)dataSource
//{
//    if(!_dataSource)
//      {
//        _dataSource = [NSMutableArray array];
//      }
//    return _dataSource;
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    if(self.editAddressModel.addressId){
        self.title = @"编辑地址";
    }else{
        self.title = @"新增地址";
    }
    [self getAreas];
    FlyWeakSelf
    [[NSNotificationCenter defaultCenter] addObserverForName:UITextFieldTextDidChangeNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        [weakSelf checkInputStatus];
    }];

//    //Keyboard
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
//
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (EJSAddressModel *)editAddressModel{
    if(!_editAddressModel){
        _editAddressModel = [[EJSAddressModel alloc] init];
    }
    return _editAddressModel;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.saveAddressButton.frame = CGRectMake(25, self.tableView.height - 75 + self.tableView.contentOffset.y, self.tableView.width - 50, 50);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//    //键盘升起，view向上偏移
//- (void)keyBoardWillShow:(NSNotification *)notification
//{
//    CGFloat duration = [[notification.userInfo valueForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
//    CGRect value = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
//    if ([self isCanMoveForKeyboard]) {
//        CGFloat keyDelta = ScreenHeight - value.size.height;
//        CGFloat maxtY = CGRectGetMaxY(self.previousTextField.superview.superview.frame);
//        CGFloat delta = ScreenHeight - maxtY;
//        if (delta <= keyDelta) {
//            CGFloat offetY = keyDelta - fabs(delta);
//            [UIView animateWithDuration:duration animations:^{
//                self.tableView.transform = CGAffineTransformMakeTranslation(0, -(offetY + self.previousTextField.frame.size.height));
//            }];
//        }
//    }else {return;}
//}
//
//    //键盘落下，view向下偏移
//- (void)keyBoardWillHide:(NSNotification *)notification
//{
//    CGFloat duration = [[notification.userInfo valueForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
////    CGRect value = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
//    [UIView animateWithDuration:duration animations:^{
//        self.tableView.transform = CGAffineTransformIdentity;
//    }];
//}
/// 是否跟随键盘移动
- (BOOL)isCanMoveForKeyboard {
    if (self.previousTextField == self.cityTextField ||
        self.previousTextField == self.streetTextField ||
        self.previousTextField == self.postcodeTextField ||
        self.previousTextField == self.emailTextField ||
        self.previousTextField == self.remarkTextField ||
        self.previousTextField == self.wechatNameTextField) {
        return YES;
    }
    return NO;
}

- (UIButton *)saveAddressButton{
    if(!_saveAddressButton)
    {
        _saveAddressButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_saveAddressButton setTitleColor:kWhiteColor forState:UIControlStateNormal];
        [_saveAddressButton setBackgroundImage:[UIImage fly_imageWithColor:AppMainColor] forState:UIControlStateNormal];
        [_saveAddressButton setTitleColor:UIColorFromRGB(0x3C4151) forState:UIControlStateDisabled];
        [_saveAddressButton setBackgroundImage:[UIImage fly_imageWithColor:UIColorFromRGB(0xD0D5D8)] forState:UIControlStateDisabled];
        _saveAddressButton.cornerRadius = 4;
        [_saveAddressButton setTitle:@"保存收货地址" forState:UIControlStateNormal];
        [_saveAddressButton addTarget:self action:@selector(saveAddressAction:) forControlEvents:UIControlEventTouchUpInside];
        _saveAddressButton.enabled = NO;
    }
    return _saveAddressButton;
}

- (void)setCountry:(EJSAreaModel *)country{
    if(_country != country){
        _country = country;
        self.province = nil;
        self.city = nil;
        self.countryLabel.text = _country.name;
        self.editAddressModel.areaId = _country.areaId;
    }
    [self checkInputStatus];
}

- (void)setProvince:(EJSAreaModel *)province{
    if(_province != province){
        _province = province;
//        self.city = nil;
        self.provinceLabel.text = _province.name;
        self.editAddressModel.areaId = _province.areaId;
    }
    [self checkInputStatus];
}

- (void)setCity:(EJSAreaModel *)city{
    _city = city;
    self.cityTextField.text = _city.name;
    [self checkInputStatus];
}

- (void)configOwnViews
{
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 100, 0);
    [self.tableView addSubview:self.saveAddressButton];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"back_icon"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(leftItemClikedAction)];
    self.nameTextField.text = self.editAddressModel.man;
    self.phoneTextField.text = self.editAddressModel.phone;
    
    if(self.editAddressModel.areaJson.count == 1){
        self.countryLabel.text = self.editAddressModel.areaJson.firstObject;
    }
    if(self.editAddressModel.areaJson.count == 2){
        self.countryLabel.text = self.editAddressModel.areaJson[0];
        self.provinceLabel.text = self.editAddressModel.areaJson[1];
    }
    if(self.editAddressModel.areaJson.count == 3){
        self.countryLabel.text = self.editAddressModel.areaJson[0];
        self.provinceLabel.text = self.editAddressModel.areaJson[1];
        self.cityTextField.text = self.editAddressModel.areaJson[2];
    }

//    self.provinceLabel.text = self.editAddressModel.province;
//    self.cityTextField.text = (self.editAddressModel.city != NULL && self.editAddressModel.city.length > 0) ? self.editAddressModel.city : self.editAddressModel.cityName;
    
    self.streetTextField.text = self.editAddressModel.address;
    self.postcodeTextField.text = self.editAddressModel.postcode;
//    self.companyNameTextField.text = self.editAddressModel.company;
//    self.taxNumberTextField.text = self.editAddressModel.dutyNum;
//    [self.isTaxCompany setOn:[self.editAddressModel.dutyType isEqualToString:@"0"]];
    self.wechatNameTextField.text = self.editAddressModel.wechat;
    self.emailTextField.text = self.editAddressModel.email;
    self.remarkTextField.text = self.editAddressModel.remark;
    self.defaultAddressButton.selected = self.editAddressModel.defaultFlag.integerValue == 1;
    [self checkInputStatus];
}

- (void)initAddressModel {
    
    for (EJSAreaModel *model in self.dataSource) {
        if ([model.name isEqualToString:self.countryLabel.text]) {
            _country = model;
        }
    }

}

- (void)leftItemClikedAction {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)getAreas{
    EJSGetAreaRequest *req = [EJSGetAreaRequest new];
    [[HUDHelper sharedInstance] syncLoading];
    FlyWeakSelf
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] syncStopLoading];
        if(response.data){
            weakSelf.dataSource = [NSMutableArray arrayWithArray:response.data];
            [weakSelf initAddressModel];
        }
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] syncStopLoading];
        [[HUDHelper sharedInstance] tipMessage:response.message];
    }];
}

- (void)checkInputStatus{
    if(self.nameTextField.text.length > 0 && self.phoneTextField.text.length > 0 && self.provinceLabel.text > 0 && self.cityTextField.text > 0 && self.streetTextField.text.length > 0 && self.postcodeTextField.text.length > 0){
        _saveAddressButton.enabled = YES;
    }else{
        _saveAddressButton.enabled = NO;
    }
}

#pragma mark - Actions

- (IBAction)defaultAddressAction:(UIButton *)sender {
    sender.selected = !sender.selected;
}

- (IBAction)companyTaxChanged:(UISwitch *)sender {
    [sender setOn:!sender.isOn animated:YES];
}

- (void)saveAddressAction:(UIButton *)button{
    NSString *phone = self.phoneTextField.text;
    NSString *name = self.nameTextField.text;
    NSString *street = self.streetTextField.text;
    NSString *postcode = self.postcodeTextField.text;
//    NSString *company = self.companyNameTextField.text;
//    NSString *dutyNum = self.taxNumberTextField.text;
//    NSString *dutyTyoe = self.isTaxCompany.isOn ?@"0":@"1";
    NSString *wechat = self.wechatNameTextField.text;
    NSString *email = self.emailTextField.text;
    NSString *remark = self.remarkTextField.text;

    EJSEditAddressRequest *req = [[EJSEditAddressRequest alloc] init];
    req.phone = phone;
    req.man = name;
    req.address = street;
    req.postcode = postcode;
    req.addressId = self.editAddressModel.addressId;
    req.areaId = self.editAddressModel.areaId;
    req.defaultFlag = self.defaultAddressButton.selected?@"1":@"0";
//    req.provinceId = self.editAddressModel.provinceId;
    req.areaJson = [NSString stringWithFormat:@"[\"%@\",\"%@\",\"%@\"]",self.countryLabel.text, self.provinceLabel.text, self.cityTextField.text];
//    req.cityName = self.cityTextField.text;
//    req.company = company;
//    req.dutyNum = dutyNum;
//    req.dutyType = dutyTyoe;
    req.wechat = wechat;
    req.email = email;
    req.remark = remark;

    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [self leftItemClikedAction];
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:response.message];
    }];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 12;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    [super tableView:tableView didSelectRowAtIndexPath:indexPath];
    [self.tableView endEditing:YES];
    if(indexPath.row == 3){
        if(self.dataSource){
            NSMutableArray *array = [NSMutableArray array];
            for (EJSAreaModel *model in self.dataSource) {
                [array addObject:model.name?model.name:@""];
            }
            FlyWeakSelf
            [DJShowSelectTool showSelectWithArr:array andDefaultStr:self.countryLabel.text complete:^(NSString *selectedStr, NSInteger num) {
                weakSelf.country = [self.dataSource objectAtIndex:num];
            }];
        }
    }
    if(indexPath.row == 4){
        if(self.country){
            NSMutableArray *array = [NSMutableArray array];
            for (EJSAreaModel *model in self.country.sons) {
                [array addObject:model.name?model.name:@""];
            }
            FlyWeakSelf
            [DJShowSelectTool showSelectWithArr:array andDefaultStr:self.provinceLabel.text complete:^(NSString *selectedStr, NSInteger num) {
                weakSelf.province = [self.country.sons objectAtIndex:num];
            }];
        }else{
            [[HUDHelper sharedInstance] tipMessage:@"请先选择国家"];
        }
    }

}

/*

 //    if(indexPath.row == 4){
 //        if(!self.province){
 //            [[HUDHelper sharedInstance] tipMessage:@"请先选择省份"];
 //            return;
 //        }
 //        if(self.province.sons){
 //            NSMutableArray *array = [NSMutableArray array];
 //            for (EJSAreaModel *model in self.province.sons) {
 //                [array addObject:model.name?model.name:@""];
 //            }
 //            FlyWeakSelf
 //            [DJShowSelectTool showSelectWithArr:array andDefaultStr:self.cityLabel.text complete:^(NSString *selectedStr, NSInteger num) {
 //                weakSelf.city = [self.province.sons objectAtIndex:num];
 //            }];
 //        }
 //    }
 */

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.saveAddressButton.frame = CGRectMake(25, self.tableView.height - 75 + scrollView.contentOffset.y, self.tableView.width - 50, 50);
}

    //MARK: textFieldDelegate 代理
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    self.previousTextField = textField;
}

///点击 下一个自动成为响应者
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == self.nameTextField) {
        [self.phoneTextField becomeFirstResponder];
    }else if (textField == self.phoneTextField) {
        [self.cityTextField becomeFirstResponder];
    }else if (textField == self.cityTextField) {
        [self.streetTextField becomeFirstResponder];
    }else if (textField == self.streetTextField) {
        [self.postcodeTextField becomeFirstResponder];
    }else if (textField == self.postcodeTextField) {
        [self.wechatNameTextField becomeFirstResponder];
    }else if (textField == self.wechatNameTextField) {
        [self.emailTextField becomeFirstResponder];
    }else if (textField == self.emailTextField) {
        [self.remarkTextField becomeFirstResponder];
    }else {
        [textField resignFirstResponder];
    }
    return YES;
}
@end
